#include "ExGameTimer.h"
#include <windows.h>

ExGameTimer::ExGameTimer(QObject *parent)
	: QObject(parent), SecondsPerCount(0.0), DeltaSeconds(0.0), BaseTime(0), StopTime(0),
	PausedTime(0), PrevTime(0), CurrTime(0), IsStopped(false)
{
	__int64 CountsPerSec;
	QueryPerformanceFrequency((LARGE_INTEGER*)&CountsPerSec);
	SecondsPerCount = 1.0 / (double)CountsPerSec;
}

ExGameTimer::~ExGameTimer()
{
}

float ExGameTimer::TotalTime() const
{
	if (IsStopped)
	{
		return (float)(((StopTime - PausedTime) - BaseTime)* SecondsPerCount);
	}
	else
	{
		return (float)(((CurrTime - PausedTime) - BaseTime)* SecondsPerCount);
	}
}

float ExGameTimer::DeltaTime() const
{
	return (float)DeltaSeconds;
}

void ExGameTimer::Reset()
{
	__int64 NowTime;
	QueryPerformanceCounter((LARGE_INTEGER*)&NowTime);

	BaseTime = NowTime;
	PrevTime = NowTime;
	StopTime = 0;
	PausedTime = 0;	// 涉及到多次Reset的话需要将其归0
	IsStopped = false;
}

void ExGameTimer::Start()
{
	__int64 StartTime;
	QueryPerformanceCounter((LARGE_INTEGER*)&StartTime);

	if (IsStopped)
	{
		PausedTime += (StartTime - StopTime);

		PrevTime = StartTime;
		StopTime = 0;
		IsStopped = false;
	}
}

void ExGameTimer::Stop()
{
	if (!IsStopped)
	{
		__int64 NowTime;
		QueryPerformanceCounter((LARGE_INTEGER*)&NowTime);

		StopTime = NowTime;
		IsStopped = true;
	}
}

void ExGameTimer::Tick()
{
	if (IsStopped)
	{
		DeltaSeconds = 0.0;
		return;
	}

	__int64 NowTime;
	QueryPerformanceCounter((LARGE_INTEGER*)&NowTime);

	CurrTime = NowTime;
	DeltaSeconds = (CurrTime - PrevTime) * SecondsPerCount;
	PrevTime = CurrTime;
	if (DeltaSeconds < 0.0)
	{
		DeltaSeconds = 0.0;
	}
}

